<template>
	<view class="">
		<!-- <text class="code-btn" @click="sendSmsCode"> {{codeDuration ? codeDuration + 's' : '获取验证码' }}</text> -->
		<button @click="sendCode">{{ codeDuration ? `${ codeDuration } s` : '获取验证码' }}</button>
	</view>
</template>

<script>
	import {
		AuthModel
	} from "@/common/apis/auth.js"
	let authModel = new AuthModel()

	let interval = null
	export default {
		props: {
			mobile: {
				type: String,
				default: () => ''
			},
			templateCode: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				codeDuration: null
			}
		},
		methods: {
			// 发送验证码
			async sendCode() {
				// 更换手机号与原手机号一致，不允许发送
				if(this.$store && this.mobile === this.$store.state.userInfo.mobile){
					this.$util.mag('手机号码格式不正确')
					return
				}
				
				// 登录页面
				if (this.codeDuration) {
					uni.showModal({
						content: `请在${ this.codeDuration }秒后重试`,
						showCancel: false
					})
					return
				}

				if (!this.mobile || !this.$util.checkStr(this.mobile, 'mobile')) {
					this.$util.msg('请输入有效手机号码')
					return
				}

				try {

					uni.showLoading({
						mask: true
					})
					const {
						data: {
							code,
							message
						}
					} = await authModel.sendCode(this.mobile, this.templateCode);
					uni.hideLoading()
					this.$util.msg(message)
					if (code !== 20000) return
					// 倒计时
					this.codeDuration = 60
					interval = setInterval(() => {
						this.codeDuration--
						if (this.codeDuration === 0) {
							if (interval) {
								clearInterval(interval)
								interval = null
							}
						}
					}, 1000)
				} catch (e) {
					uni.hideLoading()
					this.$util.msg('验证码发送失败')
				}


			},
		}
	}
</script>

<style>
	button {
		position: absolute;
		bottom: 0;
		right: 0;
		background-color: #345dc2;
		border-radius: 5px;
		width: 80px;
		font-size: 24rpx;
		color: #fff
	}
</style>
